package com.longjianghuasheng.logistics.business.order.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.StrictMode
import android.text.TextUtils
import android.view.View
import androidx.activity.result.ActivityResultCallback
import androidx.core.view.isGone
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.longjianghuasheng.logistics.R
import com.longjianghuasheng.logistics.base.BaseTitleFragment
import com.longjianghuasheng.logistics.business.order.adapter.FileAdapter
import com.longjianghuasheng.logistics.business.order.contract.ResultContract
import com.longjianghuasheng.logistics.business.order.viewmodel.SignUpViewModel
import com.longjianghuasheng.logistics.databinding.FragmentSignUpBinding
import com.longjianghuasheng.logistics.entity.FileItem
import com.longjianghuasheng.logistics.entity.SignInfo
import com.longjianghuasheng.logistics.ext.*
import com.longjianghuasheng.logistics.util.CacheUtil
import com.longjianghuasheng.logistics.util.OpenFileUtil
import com.longjianghuasheng.logistics.util.PickUtils
import com.luck.picture.lib.entity.LocalMedia
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet.BottomListSheetBuilder
import me.hgj.jetpackmvvm.ext.view.gone
import me.hgj.jetpackmvvm.ext.view.visible


class SignUpFragment : BaseTitleFragment<SignUpViewModel, FragmentSignUpBinding>() {


    private val serverFileAdapter by lazy {
        FileAdapter().apply { isSigning = true }
    }
    private val localFileAdapter by lazy {
        FileAdapter()
    }

    override fun layoutId(): Int = R.layout.fragment_sign_up

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initTitleBar("签约页面")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            val builder = StrictMode.VmPolicy.Builder()
            StrictMode.setVmPolicy(builder.build())

        }
        mDatabind.run {
            initRecycler()
            initListener()

        }
    }


    private fun FragmentSignUpBinding.initListener() {

        btnSelect.setOnClickListener {
            filePermission {
                showSimpleBottomSheetList()
            }
        }
        btnConfirm.setOnClickListener {
            with(mViewModel) {
                list.clear()
                list.addAll(localFileAdapter.data.map { it.path })
                sign_files()
            }
        }
        val block = { path: String ->
            filePermission {

                openFile(path)
            }

        }
        serverFileAdapter.run {
            addChildClickViewIds(R.id.iv_download)

            setOnItemChildClickListener { adapter, view, position ->
                if (view.id == R.id.iv_download) block.invoke(data[position].path)

            }

        }

        localFileAdapter.run {


            addChildClickViewIds(R.id.tv_delete, R.id.iv_download)

            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.iv_download -> block.invoke(data[position].path)
                    R.id.tv_delete -> {
                        removeAt(position)
                    }
                    else -> {}
                }

            }
        }
    }


    private fun FragmentSignUpBinding.initRecycler() {

        rvServerFile.initDivide(serverFileAdapter)



        rvLocalFile.initDivide(localFileAdapter)
        rvLocalFile.setHasFixedSize(false)

    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        mViewModel.result.observer(this) {

            mDatabind.setData(it)

        }
        mViewModel.notify.observer(this) {
            navigateUp()
        }
        mViewModel.fileSuccess.observer(this) {
            startActivity(it)
        }
    }

    private fun FragmentSignUpBinding.setData(it: SignInfo) {
        serverFileAdapter.setNewInstance(it.names?.mapIndexed { index, s ->
            FileItem(
                it.files?.get(
                    index
                ) ?: "", s
            )
        }?.toMutableList())
        if (it.sign_status == "已签约") {
            localFileAdapter.isSigning = true
            localFileAdapter.setNewInstance(it.namess?.mapIndexed { index, s ->
                FileItem(
                    it.signs?.get(
                        index
                    ) ?: "", s
                )
            }?.toMutableList())
            mDatabind.btnSelect.gone()
            mDatabind.btnConfirm.gone()

        }




        stvCommitDate.isGone = it.commit_date.isNullOrBlank()
        stvCommitDate.setRightString(it.commit_date)
        stvStatus.setRightString(it.sign_status)


        stvSignDate.isGone = it.sign_date.isNullOrBlank()
        stvSignDate.setRightString(it.sign_date)
        llContainer.visible()
    }


    override fun initData() {
        super.initData()
        mViewModel.id = arguments?.getInt("id") ?: 0
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.sign_info()


    }

    private fun openFile(fileUri: String) {
        if (TextUtils.isEmpty(fileUri)) {

            toastNormal("文件路径无效！")
            return
        }
        //不是网络文件
        if (!fileUri.contains("http") && !fileUri.contains("https")) {

            LogUtils.d(SignUpViewModel.TAG, "3333333333333")
//            startActivity(fileUri)
            return
        }

        val cacheFilePath: String = CacheUtil.getFilePath(fileUri) ?: ""
        //文件缓存存在
        if (!TextUtils.isEmpty(cacheFilePath) && FileUtils.isFileExists(cacheFilePath)) {

            startActivity(cacheFilePath)
            LogUtils.d(SignUpViewModel.TAG, "111111111111111=cacheFilePath=$cacheFilePath")
            return
        }


        //没有缓存，下载
        LogUtils.d(SignUpViewModel.TAG, "222222222")

        mViewModel.startDownload(fileUri)

    }

    private fun startActivity(filePath: String) {

        startActivity(OpenFileUtil.openFile(filePath))

    }


    private val launcher =
        registerForActivityResult(ResultContract(), object : ActivityResultCallback<Intent?> {
            override fun onActivityResult(result: Intent?) {
                if (result == null) {
                    return
                }
                val uri = result.data
                //文件路径
                val mFilePath = PickUtils.getPath(context, uri)
                //文件名
                val mFileName = PickUtils.getFileName(requireContext(), uri)

                LogUtils.d("mFilePath=$mFilePath---------------mFileName=$mFileName")

                localFileAdapter.addData(FileItem(mFilePath, mFileName))
            }
        })

    // ================================ 生成不同类型的BottomSheet
    private fun showSimpleBottomSheetList() {
        BottomListSheetBuilder(context)
            .setTitle("文件方式")
            .addItem("拍摄照片")
            .addItem("相册照片")
            .addItem("选择文件")
            .setIsCenter(true)
            .setOnSheetItemClickListener { dialog: BottomSheet, itemView: View?, position: Int, tag: String? ->
                dialog.dismiss()

                val block: (LocalMedia) -> Unit = {

                    localFileAdapter.addData(FileItem(it.realPath, it.fileName))

                }
                when (position) {
                    0 -> photograph(block)
                    1 -> selectPicture(block)
                    2 -> launcher.launch(true)
                    else -> {}
                }

            }
            .build()
            .show()
    }

    companion object {
        private const val TAG = "SignUpFragment"
    }
}